package java_zhuoer_adv3;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.*;

public class StuManager extends Thread {
	Map<String, Student> admin = null;
	final String objpath = "stu.obj";

	public StuManager() {
		try {
			ObjectInputStream oin = new ObjectInputStream(new FileInputStream(
					objpath));
			admin = (Map<String, Student>) oin.readObject();
			oin.close();
		} catch (Exception e) {
			// e.printStackTrace();
			admin = new HashMap<String, Student>();
		}

	}

	@Override
	public void run() {
		while (true) {
			try {
				sleep(20 * 1000);
				//
				try {
					ObjectOutputStream oout = new ObjectOutputStream(
							new FileOutputStream(objpath));
					oout.writeObject(admin);
					oout.close();
					System.out.println("已自动保存！");
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}

				//
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}

		}
	}

	public void work() {

		Scanner input = new Scanner(System.in);

		// 初始化。
		// 读取外部对象到admin中

		while (true) {
			System.out.println("1.显示 2.新增 3.删除 4.修改 5.退出");
			System.out.print("请输入选择:");
			int num = input.nextInt();
			switch (num) {
			case 1:
				System.out.println(admin);
				break;
			case 2:
				System.out.print("请输入学号:");
				String stuNumber = input.next();
				System.out.print("请输入年龄:");
				int age = input.nextInt();
				System.out.print("请输入姓名:");
				String name = input.next();
				System.out.print("请输入身份证号码:");
				String IDNumber = input.next();
				Student student = new Student(stuNumber, age, name, IDNumber);
				boolean isExist = admin.containsKey(stuNumber);
				if (isExist) {
					System.out.println("此学生已存在！");
				} else {
					admin.put(stuNumber, student);
				}
				break;
			case 3:
				System.out.print("请输入要删除学号:");
				String stuNum = input.next();
				Object o = admin.remove(stuNum);
				if (o != null) {
					System.out.println("删除成功！");
				} else {
					System.out.println("查无此人");
				}
				break;
			case 4:

				break;
			case 5:
				try {
					ObjectOutputStream oout = new ObjectOutputStream(
							new FileOutputStream(objpath));
					oout.writeObject(admin);
					oout.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
				System.out.println("程序结束");
				System.exit(0);
				return;
			default:
				System.out.println("输入错误！请重新选择！");
			}
			System.out.println();
		}

	}

	public static void main(String[] args) {
		StuManager s = new StuManager();
		s.start();
		s.work();

	}

}
